import 'dart:async';

import 'package:flutter/material.dart';

class BannerView<T> extends StatefulWidget {
  final List<T> data;
  final Duration pageSwitchDuration;

  ///构造方法
  BannerView(
      {@required this.data,
      this.pageSwitchDuration = const Duration(seconds: 3)});


  @override
  _BannerViewState createState() => _BannerViewState();
}

class _BannerViewState extends State<BannerView>
    with SingleTickerProviderStateMixin {
  TabController _tabController;

  var _pageIndex = 0;
  PageController _pageController;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _tabController = TabController(length: widget.data.length, vsync: this);
    _pageController = PageController(initialPage: 0);
    Timer(Duration(
      seconds: 3
    ),_nextPage);
  }

  void _nextPage(){
    _pageIndex++;
    _pageController.animateToPage(_pageIndex, duration: widget.pageSwitchDuration, curve: Curves.linear);

  }
  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        PageView.builder(
            controller: _pageController,
            itemCount: widget.data.length,
            itemBuilder: (context, i) => _itemBuilder(i),
        onPageChanged: (int index){
          _pageIndex = index;
              _tabController.animateTo(index,duration: Duration(milliseconds: 500),
              );
        },),
        Positioned(
          bottom: 8.0,
          right: 8.0,
          child: TabPageSelector(
            controller: _tabController,
            color: Colors.white,
            selectedColor: Colors.lightBlueAccent,
          ),
        ),
      ],
    );
  }

  Widget _itemBuilder(int index) {
    return Image.network(
      widget.data[index],
      fit: BoxFit.cover,
    );
  }
}
